
/**
	This file is part of MemoryTrace.

	MemoryTrace is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

        Contributed by Ameziane NAIT ABDELAZIZ.
        
	MemoryTrace is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
**/


#include "ReaderStatusProc.h"
#include <cstdio>
#include <string.h>
#include <cstdlib>
#include <unistd.h>
#include <sched.h>
#include <stdio.h>
#include <cassert>
#include <sys/types.h>
#include <sys/wait.h>



/*signal de quit*/
void process_end(int sig) {
  printf("Killed from user!\n");
  (void) signal(SIGINT, SIG_DFL);
  //Ici le code de finalization
  printf("Bye Bye!\n");
  exit(0);
}

/*affiche l'aide*/
static inline void showHelp(){
  printf("\033[34;1mtop[kb|mb|gb]       : realise une mesure sur le processus instrumenté avec l'unité en suffixe de la commande\033[m\n");
  printf("\033[34;1mhelp                : affiche cette aide\033[m\n");
  printf("\033[34;1mquit                : quitte le programme\033[m\n");
}

/*affiche le header*/
static inline void showHeader(){
  printf("          Memory status proc.\n");
  printf("Tape help for immediate help.\n");
}


/*programme principal*/
int main(int argc,char* argv[]){
  
  pid_t pid;
  if(argc==2){
    (void) signal(SIGINT, process_end);
    pid=(pid_t)atoi(argv[1]);
    showHeader();
  }
  
  else{
    printf("Usage: ./proc_status [pid]\n");
    printf("Tape help for immediate help\n");
    return EXIT_SUCCESS;
  }
  
  status_t st;
  long int i=0;
  char commande[1024];
  
  while(true){
    i++;
    printf("status>");
    scanf("%s",commande);
    
    if(strncmp(commande,"top",3)==0){
      
      if(strlen(commande)==3){
        ReaderStatusProc::dumpSelfStatus("BIN");
      }
      
      ReaderStatusProc::getStatus(pid,st);
      
      
      if(strncmp(commande,"topmb",7)==0){
	ReaderStatusProc::printStatus(st,st.name,1024,"MB");
      }
      
      
      if(strncmp(commande,"topkb",6)==0){
	ReaderStatusProc::printStatus(st,st.name,1,"KB");
      }
      
      if(strncmp(commande,"topgb",6)==0){
	ReaderStatusProc::printStatus(st,st.name,1024*1024,"GB");
      }
      
    }
    else{ 
      if(strncmp(commande,"help",4)==0){
	showHelp();
      }
      else{
	if(strncmp(commande,"quit",4)==0){
	  return 0;
	}
      }
      
    }
  }
  return 0;
}
